package javawdw.io.simple;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;

import javawdw.io.TextWriter;

/**
 * 文本文件写入器<br>
 * 带BOM头的UTF-8文件请使用如下代码<br>
 * byte[] bomHead = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; <br>
 * writer.write(new String(bomHead));
 * 
 * @author David
 * 
 */
public class BufferedTextWriter implements TextWriter {
	private PrintWriter writer;
	private OutputStreamWriter osw;
	private OutputStream outputStream;

	/**
	 * 根据给定输出流创建文本文件写入器
	 * 
	 * @param outputStream
	 *            给定的输出流
	 * @param charsetName
	 *            给定的字符集
	 */
	public BufferedTextWriter(OutputStream outputStream, String charsetName) {
		Charset charset = Charset.forName(charsetName);
		this.outputStream = outputStream;
		this.osw = new OutputStreamWriter(outputStream, charset);
		this.writer = new PrintWriter(osw);
	}

	/**
	 * 根据给定输出流创建文本文件写入器
	 * 
	 * @param outputStream
	 *            给定的输出流
	 * @param charsetName
	 *            给定的字符集
	 */
	public BufferedTextWriter(OutputStream outputStream) {
		this(outputStream, Charset.defaultCharset().name());
	}

	/**
	 * 将给定内容写入文件,并换行
	 * 
	 * @param any
	 *            要写入的内容
	 */
	public void writeLine(String str) {
		writer.println(str);
	}

	/**
	 * 将给定内容写入文件
	 * 
	 * @param any
	 *            要写入的内容
	 */
	public void write(String str) {
		writer.print(str);
	}

	/**
	 * 刷新写入器
	 */
	public void flush() {
		try {
			outputStream.flush();
		} catch (IOException e) {
		}
	}

	/**
	 * 关闭写入器
	 */
	public void close() {
		try {
			this.flush();
			writer.close();
			this.osw.close();
		} catch (IOException e) {
		}
	}
}
